package com.jk.util.autotest.util;

import com.jk.util.autotest.model.InterfaceTestInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.util.List;

public class ExcelOutputUtil {

    private static Workbook getWriteWorkBoolType(String filePath) throws Exception {
        if (filePath.toLowerCase().endsWith("xlsx")) {
            return new XSSFWorkbook();
        } else if (filePath.toLowerCase().endsWith("xls")) {
            return new HSSFWorkbook();
        } else {
            //抛出自定的业务异常
            throw new Exception("excel格式文件错误");
        }
    }

    public static void writeExcel(String targetFilePath, List<InterfaceTestInfo> contents) throws Exception {
        Workbook workbook = null;
        FileOutputStream fos = null;
        workbook = getWriteWorkBoolType(targetFilePath);
        //创建sheet
        Sheet sheet = workbook.createSheet("门店入件状态");
        //在sheet第一行写出表单的各个字段名
        Row titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("接口名称");
        titleRow.createCell(1).setCellValue("接口地址");
        titleRow.createCell(2).setCellValue("缓存时间");
        titleRow.createCell(3).setCellValue("测试报告");
        //每行的单元格一次写入
        Integer rowIndex = contents.size();
        for (int i = 0; i < rowIndex; i++) {
            //第1行作为表格列名，所以从第2行开始读取
            Row row = sheet.createRow(i + 1);
            Cell cellName = row.createCell(0);
            cellName.setCellValue(contents.get(i).getName());
            Cell cellAddress = row.createCell(1);
            cellAddress.setCellValue(contents.get(i).getAddress());
            Cell cellSaveTime = row.createCell(2);
            cellSaveTime.setCellValue(contents.get(i).getSaveTime());
            Cell cellConclusion = row.createCell(3);
            cellConclusion.setCellValue(contents.get(i).getConclusion());
        }
        //写入到文件流中
        try {
            fos = new FileOutputStream(targetFilePath);
            workbook.write(fos);
        } catch (Exception e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(workbook);
            fos.close();
        }
    }
}
